/*
 * @Author: luoyunhai
 * @Date: 2020-12-22 16:12:36
 * @LastEditors: kanglang
 * @LastEditTime: 2021-01-26 16:38:41
 * @Description: 通讯录索引组件 section List Contacts
 */

import React, { Component } from 'react';
import {
  View,
  SectionList,
  FlatList,
  Text,
  StyleSheet,
  TouchableOpacity
} from 'react-native';
import {
  px2dp,
} from '@/styles';
import pinyin from 'pinyin';

export default class SectionListContacts extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sections: [], // section数组
      letterArr: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'], // 首字母数组
      showIndex: -1
    };
  }

  componentDidMount() {
    this.initSectionListContacts();
  }

  componentDidUpdate(prevProps) {
    const { source } = this.props;
    if (prevProps.source !== source) {
      this.initSectionListContacts();
    }
  }

  render() {
    const { letterArr, sections } = this.state;
    const { renderItem, isShowIndexes = false } = this.props;
    return (
      <View style={{ flex: 1 }}>
        <SectionList
          ref='_sectionList'
          renderItem={renderItem}
          renderSectionHeader={this._renderSectionHeader}
          sections={sections}
          keyExtractor={(item, index) => item + index}
          ItemSeparatorComponent={() => <View />}
        />

        {/* 右侧字母栏 */}
        {
          isShowIndexes && (
            <View style={styles.rightCase}>
              <FlatList
                data={letterArr}
                keyExtractor={(item, index) => index.toString()}
                renderItem={({ item, index }) => (
                  <TouchableOpacity
                    onPress={() => {
                      this._onSectionSelect(index);
                    }}
                  >
                    <Text style={styles.indexCase}>{item.toUpperCase()}</Text>
                  </TouchableOpacity>
                )}
              />
            </View>
          )
        }
      </View>
    );
  }

  // 字母关联分组跳转
  _onSectionSelect = (key) => {
    this.refs._sectionList.scrollToLocation({
      itemIndex: 0,
      sectionIndex: key,
      viewOffset: 0,
    });
  };

  // 分组列表的头部
  _renderSectionHeader = (sectionItem) => {
    const { section } = sectionItem;
    return (
      <View style={styles.sectionHeader}>
        <Text style={styles.headerTitle}>{section.title.toUpperCase()}</Text>
      </View>
    );
  }

  initSectionListContacts = () => {
    const { source, firstWord = 'userName' } = this.props;
    let sections = [];
    let letterArr = [];
    // 右侧字母栏数据处理
    source.forEach((item) => {
      letterArr.push(pinyin(item[firstWord].substring(0, 1), {
        style: pinyin.STYLE_FIRST_LETTER,
      })[0][0].toUpperCase());
      letterArr = [...new Set(letterArr)].sort();
      this.setState({ letterArr: letterArr });
    });
    // 分组数据处理
    letterArr.forEach(item => {
      sections.push({
        title: item,
        data: []
      });
    });
    source.forEach(item => {
      let listItem = item;
      sections.forEach(itemOne => {
        let first = listItem[firstWord].substring(0, 1);
        let test = pinyin(first, { style: pinyin.STYLE_FIRST_LETTER })[0][0].toUpperCase();
        if (itemOne.title === test) {
          itemOne.data.push(item);
        }
      });
    });
    this.setState({ sections: sections });
  }
}

const styles = StyleSheet.create({
  rightCase: {
    position: 'absolute',
    right: px2dp(10),
    top: '20%'
  },
  sectionHeader: {
    height: px2dp(48),
    backgroundColor: '#F9F9FB',
    paddingLeft: px2dp(32)
  },
  headerTitle: {
    lineHeight: px2dp(48),
  },
  indexCase: {
    color: '#919399',
    fontSize: px2dp(28)
  }
});
